var MailMain = Class.create();
MailMain.prototype = {
	initialize: function() {
		
	}
};

function searchSogou(input_id) {
	var sgi = $(input_id),
	url = 'http://www.sogou.com/web?ie=utf8&query=',
	isa = sgi.getAttribute('isActive'),
	v = isa && isa == 'true' ? sgi.value : '',
	par = encodeURIComponent(v);
	window.open(url + par);
	if(isa) sgi.value = '';
}

function searchMail() {
	mailSearch.startSearch('search_mail_content');
}

function isOpenSearch() {
	openSearchModule ? (function() {
		$('search_mail_input').show();
		$('search_input').hide();
	})() : (function() {
		$('search_input').show();
		$('search_mail_input').hide();
	})();
}

// 动态载入passport JS文件，并且判断载入完毕后执行绘制卡片和组的函数
function JSLoadPP() {
	PassportSC.logoutHandle = function(ele, lfc, lsc) {
		if (typeof(ele) != "object") {
			return false;
		}
		// var logout_status = "";
		if (this.domain == "") {
			this.domain = this.getDomain();
		}
		var ra = this.getTime();
		var url = 'http://passport.sohu.com/sso/logout.jsp?s=' + ra + '&appid=' + this.appid;
		if (this.domain != "sohu.com") {
			url += "&domain=" + this.domain;
		}
		var self = this;
		loadScript(url, function() {
			self.logoutIntervalProc(lfc, lsc, ele);
		});
	};
	
	PassportSC.logoutIntervalProc = function(lfc, lsc, ele) {
		if (this.logoutRedirectUrl == "") {
			this.autoProcAllDomain("logout", ele);
		} else {
			this.addCookie("crossdomain_logout", this.getTime(), 336);
		}
		// window.location.href = 'http://mail.' + localPostfix;
		var rdurl = USE_SYS.name == 'vip.sohu' ? USE_SYS.protocol + '//vip.' : USE_SYS.protocol + '//mail.'
		window.top.location.href = rdurl + localDomain;
	};  
	try {
		PassportSC.cookieHandle();
		if(USE_SYS.name != 'vip.sohu') loadPassportGroup();
	} catch(e) {}
	try {
		RECORD_LOAD_TIME.push(+new Date());
	} catch(e) {}
}

// 显示换肤部分
function showChangeSkin(event, el) {
	var s = ['<li style="margin:2px;float:left;"><a hidefocus="true" href="javascript:;" onclick="changeMailSkin(\'default\');return false;" >',
             '<div class="am skin_default" onmouseover="Element.addClassName(this,\'skin_default_over\');" onmouseout="Element.removeClassName(this,\'skin_default_over\');"><p> </p></div>',
      		 '</a></li>',
      		 '<li style="margin:2px;float:left;"><a hidefocus="true" href="javascript:;" onclick="changeMailSkin(\'red\');return false;" >',
        	 '<div class="am skin_red" onmouseover="Element.addClassName(this,\'skin_red_over\');" onmouseout="Element.removeClassName(this,\'skin_red_over\');"><p> </p></div>',
      		 '</a></li>',
      		 '<li style="margin:2px;float:left;"><a hidefocus="true" href="javascript:;" onclick="changeMailSkin(\'blue\');return false;" >',
        	 '<div class="am skin_blue" onmouseover="Element.addClassName(this,\'skin_blue_over\');" onmouseout="Element.removeClassName(this,\'skin_blue_over\');"><p> </p></div>',
      		 '</a></li>',
      		 '<li style="margin:2px;float:left;"><a hidefocus="true" href="javascript:;" onclick="changeMailSkin(\'green\');return false;" >',
             '<div class="am skin_green" onmouseover="Element.addClassName(this,\'skin_green_over\');" onmouseout="Element.removeClassName(this,\'skin_green_over\');"><p> </p></div>',
      		 '</a></li>',
      		 '<li style="margin:2px;float:left;"><a hidefocus="true" href="javascript:;" onclick="changeMailSkin(\'grey\');return false;" >',
        	 '<div class="am skin_grey" onmouseover="Element.addClassName(this,\'skin_grey_over\');" onmouseout="Element.removeClassName(this,\'skin_grey_over\');"><p> </p></div>',
      	     '</a></li>'].join('');
	menu.showMenu(el.parentNode, DOM.navbg, s, null, true, null, event);
	if(menu.menuIfr) menu.menuIfr.style.display = 'none';
}


// 积分显示
// 放在Ajax接口中做，这个mailScore作为score_get的回调函数
var SCORE_TYPE = [
  ['silver', 1], 500, ['silver', 2], 900, ['silver', 3], 1500,
  ['golden', 1], 2700, ['golden', 2], 4500, ['golden', 3], 12500,
  ['diamond', 1], 20500, ['diamond', 2], 28500, ['diamond', 3], 36500,
  ['crown', 1], 66500, ['crown', 2], 156000, ['crown', 3]
];
    
function mailScore(ret) {
  	if (typeof(ret.totalscore) == "undefined" && typeof(ret.freescore) == "undefined") return;
  	if (ret.totalscore < 0) return;
  	__SCORE[0] = ret.totalscore;
  	__SCORE[1] = ret.freescore;
  	for (var i = SCORE_TYPE.length - 2; i >= 1; i -= 2)
    	if (ret.totalscore >= SCORE_TYPE[i]) break;
  	var img_type = SCORE_TYPE[i > 0 ? i + 1 : 0];
  	// var imgs = [['<img title="可用积分：', ret.freescore, '" src="', MailConst.ALL, '/', img_type[0], '.gif" />'].join('')];
	var imgs = ['<a class="f-lf" href="http://score.mail.sohu.com/prerogative.action" target="_blank"><span style="cursor:pointer;" class="am score-'+ img_type[0] +'" title="可用积分：'+ ret.freescore +'"></span></a>'];
  	for (var i = img_type[1] - 1; i > 0; i--) imgs.push(imgs[0]);
	// var _mail_score_img = $('mail_score_img');
  	// $('mail_score').innerHTML = ret.totalscore;
  	// _mail_score_img.innerHTML = imgs.join('');
	
	var _t = '<div class="u-item">'+ imgs.join('') +'</div><div class="u-item">积分：<span>'+ ret.totalscore +'</span></div><div class="u-item"><a href="http://score.mail.sohu.com/product.action" target="_blank">积分换礼</a></div>';
	$('score_info').innerHTML = _t;
	return false;
	
	//可兑换奖品
  	productinfo = ret.productlist;
  	var temp = ['　奖品：'];
	for(var i=0,len=productinfo.length; i<len; i++) {
		temp.push('<a hidefocus="true" onclick="jsoplog.ucCapture(\''+ productinfo[i][0]+i +'\');" href="'+productinfo[i][1]+'"  target="_blank"/><img src="'+productinfo[i][2]+'" align="absmiddle"  style="width:'+productinfo[i][3]+'px;height:'+productinfo[i][4]+'px;border: 1px solid #ffc23c;" /></a>&nbsp;');
		// temp.push('<a hidefocus="true" onclick="jsoplog.ucCapture(\'prize_'+ i +'\');" href="http://score.mail.sohu.com/productinfo.action?productid='+productinfo[i][0]+'"  target="_blank"/><img src="'+productinfo[i][1]+'"  style="width:38px;height:38px;border: 1px solid #FE8820;" /></a>&nbsp;');
	}
	temp.push('<a hidefocus="true" onclick="jsoplog.ucCapture(\'prize_more\');" href="http://score.mail.sohu.com/productquery.action" style="font-size:12px;font-weight:normal;" target="_blank">更多&gt;&gt;</a>');
	$('scoremail').innerHTML = temp.join('');
}

function userGrade(totalScore){
       var userGrade;
   	   if(totalScore<1500){
    		 userGrade="银牌";
    	}
    	if(totalScore>=1500&&totalScore<12500){
    		 userGrade="金牌";
    	}
    	if(totalScore>=12500&&totalScore<36500){
    		 userGrade="钻石";
    	}
    	if(totalScore>=36500){
    		 userGrade="皇冠";
    	}
    	return userGrade;
}

// 同名升级的显示
function showUpgrade() {
	if (typeof(UPGRADE) != 'undefined' && typeof($('upgrade')) != 'undefined') {
		if (UPGRADE == -1) {
			$('upgrade').update('<b><a hidefocus="true" href="http://vip.sohu.com/convertCheckUserName.action" target="_blank">尊贵体现，瞬时拥有同名升级VIP!</a></b>');
		} else if (UPGRADE == 0) {
			$('upgrade').update("");
		} else if (UPGRADE == 1) {
			window.location.href = "http://vip.sohu.com/remindConvertedAction.action";
		}
	}
}

function setRecommend(){
	var _s1 = $('serviceContent1');
	if(_s1) $('serviceContent1').innerHTML = mm_service_c1;
}

function _setUserInfo() {
	var _first_list = isConferenceMode ? mailConference.getListCache(1, 1) : mailList.mailListCache['inbox1'][0];
	if (!_first_list || _first_list.length == 0) {
		setTimeout(arguments.callee, 500);
		return false;
	}
	var _new_list = [].concat(_first_list).slice(0, 10);
	var new_contact_unread_item, contact_unread_item, contact_item, unread_item_flag = false, item_flag = false,
	have_read = function(item) {
		return isConferenceMode ? item.unread == 0 : item.have_read;
	},
	mid = function(item) {
		return isConferenceMode ? item.thread : item.rowid;
	},
	strflag = (function() {
		return isConferenceMode ? '会话' : '邮件';
	})(),
	index = 0, flag_one = false, flag_two = false, flag_three = false, sender_obj = {},
	_nnt = $('ID_NEWNOTICE'), _flag = false;
	if(!_nnt) return false;
	for(var i=0,len=_new_list.length;i<len;i++) {
		var item_env = _new_list[i].envelope, 
		_f = item_env.from.concat(item_env.from_after_1st_unread),
		_in_c = false, _sender = {};
		_f.each(function(item) {
			var _n = mailAddressClass.addressHash.contact.email[item[1]];
			if (mailAddressClass.addressHash.contact.email[item[1]]) {
				_sender = {nick: _n, email: item[1]};
				_in_c = true;
			}
		});
		if(i == 0 && !have_read(_new_list[i]) && _in_c && !flag_one) {
			new_contact_unread_item = _new_list[i];
			sender_obj = _sender;
			flag_one = true;
		} else if(!have_read(_new_list[i]) && _in_c && !flag_two) {
			contact_unread_item = _new_list[i];
			sender_obj = _sender;
			flag_two = true;
		} else if(_in_c && !flag_three) {
			contact_item = _new_list[i];
			sender_obj = _sender;
			flag_three = true;
		}
	}
	if(new_contact_unread_item) {
		var _sb = new_contact_unread_item.envelope.subject;
		_sb = !_sb || _sb == '' ? '无标题' : _sb;
		_nnt.innerHTML = '[新'+ strflag +'] <a href="javascript:;" class="s_read_mail" mid="'+ mid(new_contact_unread_item) +'"><b>' + _sb + '</b></a>&nbsp;&nbsp;<span title="'+ _sender.email +'">发件人：<b>'+ sender_obj.nick +'</b></span>';
	} else if(contact_unread_item) {
		_nnt.innerHTML = '<b>' + sender_obj.nick + '</b> 给你发了一封邮件，快给他<a href="javascript:;" class="s_reply_mail" mid="'+ mid(contact_unread_item) +'">回复</a>吧！';
	// } else if(contact_item) {
	// 	_nnt.innerHTML = '<b>' + sender_obj.nick + '</b> 给你发了一封邮件，快给他<a href="javascript:;" class="s_reply_mail" mid="'+ mid(contact_item) +'">回复</a>吧！';
	} else {
		// _nnt.innerHTML = '关系需要常联系，给朋友发去<a href="javascript:;" class="s_compose_mail">问候</a>吧！';
		// 圣诞活动
		_nnt.innerHTML = '<a target="_blank" href="http://goto.mail.sohu.com/goto.php?code=welc_09xmas" style="color:#ff6600;">开始拜年啦！选一张喜庆的新春贺卡吧</a>';
	}
	var _uc = $('ID_UNREADCOUNT'), _uf = $('ID_UNREADFOLDER'), ff = isConferenceMode ? mailConference.F.folders : FolderList, _f = [], _u1 = 0, _u2 = 0;
	try {
		if(ff && ff.length > 0) {
			_f = ff;
		} else {
			_f = FOLDER.evalJSON().folder;
		}
		_f.each(function(item) {
			if (item.folder_id == -2) {
				_u1 = item.unread;
				_u2 = item.thread_unread;
			}
		});
	} catch(e) {}
	if(isConferenceMode) {
		_uc.innerHTML = _u2;
	} else {
		_uc.innerHTML = _u1;
	}
	_uf.innerHTML = '未读' + strflag;
}

function setUserInfo() {
	return;
	
	var _first_list = isConferenceMode ? mailConference.getListCache(1, 1) : mailList.mailListCache['inbox1'][0];
	if (!_first_list || _first_list.length == 0) {
		setTimeout(arguments.callee, 500);
		return false;
	}
	var _new_list = [].concat(_first_list).slice(0, 10);
	
	// var new_contact_unread_item, contact_unread_item, contact_item, unread_item_flag = false, item_flag = false;
	var have_read = function(item) {
		return isConferenceMode ? item.unread == 0 : item.have_read;
	},
	mid = function(item) {
		return isConferenceMode ? item.thread : item.rowid;
	},
	gsender = function(item) {
		var s = isConferenceMode ? item.envelope.from_after_1st_unread[0] : item.envelope.from[0];
		return s[0] && s[0] != '' ? s[0] : s[1];
		// return isConferenceMode ? item.envelope.from_after_1st_unread[0][1] : item.envelope.from[0][1];
	};
	/*
	strflag = (function() {
		return isConferenceMode ? '会话' : '邮件';
	})(),
	index = 0, flag_one = false, flag_two = false, flag_three = false, sender_obj = {},
	_nnt = $('ID_NEWNOTICE'), _flag = false;
	*/
	var _unread_item = [];
	_new_list.each(function(item) {
		if (!have_read(item) && _unread_item.length < 3) {
			var o = {};
			/*
			if(isConferenceMode) {
				o.sender = item.envelope.from_after_1st_unread[0][1];
				o.id = item.thread;
			} else {
				o.sender = item.envelope.from[0][1];
				o.id = item.rowid;
			}
			*/
			o.sender = gsender(item);
			o.id = mid(item);
			var _n = (function(m) {
				try {
					return mailAddressClass.addressHash.contact.email[m];
				} catch(e) {
					return false;
				}
			})(o.sender);
			o.sender = _n ? _n : o.sender;
			o.date = item.envelope.display_date[0];
			o.title = item.subject;
			_unread_item.push(o);
		}
	});
	// if(_unread_item.length == 0) return false;
	var _t = [];
	_t[0] = '<div id="user_tips1" class="if-item">没有新邮件？是不是朋友不知道你的邮件地址呢，<span class="clk s_compose_mail">主动告知</span>一下吧</div>',
	_t[1] = '<div id="user_tips2" class="if-item"><span class="clk s_compose_card_mail">发点好玩的</span>东西，去逗逗Ta</div>',
	_t[2] = '<div id="user_tips3" class="if-item">接下来要过什么节？<a href="http://ecard.mail.sohu.com/card/index.jsp?from=mail" target="_blank"><span class="clk">来这里看看</span></a></div>';
	_unread_item.each(function(o, index) {
		var tt = o.title.toArray().join('<wbr />');
		_t[index] = '<div class="if-item"><span class="item-1"><span class="sender">'+ o.sender +' </span><span class="s_read_mail" style="cursor:pointer;" mid="'+ o.id +'"> 给您发来了一封邮件 </span><span> '+ o.date +' </span></span><span class="item-2"> '+ tt +' </span></div>';
	});
	(DOM.user_tips ? DOM.user_tips : $('user_tips')).innerHTML = _t.join('');
	return false;
	
	/*
	if(!_nnt) return false;
	for(var i=0,len=_new_list.length;i<len;i++) {
		var item_env = _new_list[i].envelope, 
		_f = item_env.from.concat(item_env.from_after_1st_unread),
		_in_c = false, _sender = {};
		_f.each(function(item) {
			var _n = mailAddressClass.addressHash.contact.email[item[1]];
			if (mailAddressClass.addressHash.contact.email[item[1]]) {
				_sender = {nick: _n, email: item[1]};
				_in_c = true;
			}
		});
		if(i == 0 && !have_read(_new_list[i]) && _in_c && !flag_one) {
			new_contact_unread_item = _new_list[i];
			sender_obj = _sender;
			flag_one = true;
		} else if(!have_read(_new_list[i]) && _in_c && !flag_two) {
			contact_unread_item = _new_list[i];
			sender_obj = _sender;
			flag_two = true;
		} else if(_in_c && !flag_three) {
			contact_item = _new_list[i];
			sender_obj = _sender;
			flag_three = true;
		}
	}
	*/
}

//
function setSpaceSize(){
    var totalsize = FoldersData.totalSize;
	var is_use = (totalsize >= mailContentTotalSize)?"100%":Math.round((totalsize/mailContentTotalSize)*1000)/10 + "%"; 
    var html = '<div class="am schedule">'
            +'<span class="amv" id="used_percent" style="width:'+is_use+'"></span>'
            +'</div>'
            +'<div style="float:left;">总容量 <span id="quota_size">'+strfsize(mailContentTotalSize)+'</span> ，'
            +'可用 <span id="total_size">'+strfsize(parseInt(mailContentTotalSize)-parseInt(totalsize))+'</span></div><div class="am update-capacity s_mobile_mail"></div>';
    if(G.isMobileUser()){
        html = '<div style="float:left;"><img align="absmiddle" src="'+MailConst.ALL+'/icon_wuxian.jpg"/>'
            +'已用容量 <span id="total_size">'+ strfsize(totalsize) +'</span>';
    }
    $('ID_SPACESIZE').innerHTML = html;
}
// 邮箱首页个人信息，
function showUserInfo() {
	/*
	var s = '<div class="mail">'+
		    '<h3>您好，'+(PROFILE.fullname?PROFILE.fullname:SUID)+'</h3>'+
            '<div class="level" style="margin-bottom:4px;"><div style="float:left;"><span class="am icon1"></span><span>积分：<a hidefocus="true" href="http://score.mail.sohu.com/product.action" target="_blank" title="上积分兑奖品" onclick="jsoplog.ucCapture(\'mailScoreIndex\')"><b id="mail_score">12</b></a>　等级：</span><span id="mail_score_img"><span class="am score-silver" title="可用积分：12"></span></span></div><div style="float:left;margin-top:-10px;position:relative;"><span id="scoremail"></span></div></div>'+
            '<div style="clear:both;"><span class="am icon2"></span><a hidefocus="true" id="ID_UNREADCOUNT" style="font-weight:bold;margin: 0 5px 0 0;">0</a>封<a hidefocus="true" id="ID_UNREADFOLDER" style="cursor:pointer;">未读邮件</a>！</div>'+
            '<div class="prompt"><span class="am icon_score icon3"></span><span id="ID_NEWNOTICE"></span></div>'+
            '<div class="spaces" id="ID_SPACESIZE">'+
			'</div>'+
            '<p id="ID_AD_MAILINDEX" class="ads"></p>';
	$('info').innerHTML = s;
	setSpaceSize();
	setUserInfo();
	*/
	getScore();
	//推荐服务
}

// 邮箱首页个人信息，
function showUserInfo_sogou() {
	var s=[
		   // 用户信息中的头像就不显示了
		   '<div class="mail">',
		   '<h3>您好，'+(PROFILE.fullname?PROFILE.fullname:SUID)+'</h3>',
           // '<div class="level"><span class="am icon1"></span><span>积分：<a hidefocus="true" href="http://score.mail.sohu.com/product.action" target="_blank" title="上积分兑奖品" onclick="jsoplog.ucCapture(\'mailScoreIndex\')"><b id="mail_score">12</b></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;等级：</span><span id="mail_score_img"><span class="am score-silver" title="可用积分：12"></span></span><span id="scoremail" style="margin-top: -25px;position:absolute;"></span></div>',
           '<div><span class="am icon2"></span><a hidefocus="true" id="ID_UNREADCOUNT" style="font-weight:900;margin: 0 5px 0 0;cursor:pointer;">0</a>封<a hidefocus="true" id="ID_UNREADFOLDER" style="cursor:pointer;">未读邮件</a>！</div>',
           '<div class="prompt"><span class="am icon_score icon3"></span><span id="ID_NEWNOTICE"></span></div>',
           '<div class="spaces">',
           '<div class="am schedule"><span class="amv" id="used_percent"></span></div>总容量 <span id="quota_size">2.0G</span> ，可用 <span id="total_size">2G</span>',
           '</div></div>',
           '<p id="ID_AD_MAILINDEX" style="margin:10px 0 5px 0;text-align:center;">',
           // ad_mailIndex,
           '</p>'].join('');
	$('info').innerHTML = s;
	var totalsize = FoldersData.totalSize;
	var is_use = (totalsize >= mailContentTotalSize)?"100%":Math.round((totalsize/mailContentTotalSize)*1000)/10 + "%";
	$('quota_size').innerHTML = strfsize(mailContentTotalSize);
	$('total_size').innerHTML = strfsize(parseInt(mailContentTotalSize)-parseInt(totalsize));
	Element.setStyle($('used_percent'), {width : is_use});
	setUserInfo();
	//推荐服务
}

// chinaren邮箱的用户信息展示区域
function loadMailMainPage_chinaren() {
	// 载入首页的html
	try {
		var _mp = DOM.mainPage ? DOM.mainPage : $('mainPage');
		_mp.innerHTML = mailMainTemplate_chinaren;
	} catch(e) {}
	// 用户信息区域
	var s=[
		   // 用户信息中的头像就不显示了
		   '<div class="mail">',
		   '<h3>您好，'+(PROFILE.fullname?PROFILE.fullname:SUID)+'</h3>',
           // '<div class="level"><span class="am icon1"></span><span>积分：<a hidefocus="true" href="http://score.mail.sohu.com/product.action" target="_blank" title="上积分兑奖品" onclick="jsoplog.ucCapture(\'mailScoreIndex\')"><b id="mail_score">12</b></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;等级：</span><span id="mail_score_img"><span class="am score-silver" title="可用积分：12"></span></span><span id="scoremail" style="margin-top: -25px;position:absolute;"></span></div>',
           '<div><span class="am icon2"></span><a hidefocus="true" id="ID_UNREADCOUNT" style="font-weight:900;margin: 0 5px 0 0;cursor:pointer;">0</a>封<a hidefocus="true" id="ID_UNREADFOLDER" style="cursor:pointer;">未读邮件</a>！</div>',
           '<div class="prompt"><span class="am icon_score icon3"></span><span id="ID_NEWNOTICE"></span></div>',
           '<div class="spaces">',
           '<div class="am schedule"><span class="amv" id="used_percent"></span></div>总容量 <span id="quota_size">2.0G</span> ，可用 <span id="total_size">2G</span>',
           '</div></div>'].join('');
	$('info').innerHTML = s;
	var totalsize = FoldersData.totalSize;
	var is_use = (totalsize >= mailContentTotalSize)?"100%":Math.round((totalsize/mailContentTotalSize)*1000)/10 + "%";
	$('quota_size').innerHTML = strfsize(mailContentTotalSize);
	$('total_size').innerHTML = strfsize(parseInt(mailContentTotalSize)-parseInt(totalsize));
	Element.setStyle($('used_percent'), {width : is_use});
	setUserInfo();
	try {
		$('service').innerHTML = commend_chinaren;
	} catch(e) {}
}

// 邮箱系统的首页展示
function loadMailMainPage() {
	// 载入首页的html
	try {
		showMainMail();
	} catch(e) {}
	
	// 载入用户在邮箱中的相关信息
	try {
		showUserInfo();
	} catch (e) {}
	// 载入推荐信息
	try {
		setRecommend();
	} catch(e) {}
}

// sogou邮箱的首页展示
function loadMailMainPage_sogou() {
	// 载入首页的html
	try {
		showMainMail();
	} catch(e) {}
	// 载入用户在邮箱中的相关信息
	try {
		showUserInfo_sogou();
	} catch (e) {}
}

// 首次载入，判断不同的邮箱，采用不同的执行函数
function firstLoad() {
    //记录锚点
    getParametersFromUrl();
	var l = [{
		name: 'vip.sohu',
		exec: function() {
			loadMailMainPage();
		}
	}, {
		name: 'sohu',
		exec: function() {
			loadMailMainPage();
		}
	}, {
		name: 'chinaren',
		exec: function() {
			loadMailMainPage_chinaren();
		}
	}, {
		name: 'sogou',
		exec: function() {
			loadMailMainPage_sogou();
		}
	}];
	l.each(function(item) {
		if(USE_SYS.name == item.name) item.exec();
	});
}

// 显示在邮箱顶部的文字广告
function showTopAds() {
	if(_is_xj) return false;
	var imt = $('ID_MAIL_TOP');
	if(imt){
		// imt.innerHTML = mailtop1;
		imt.innerHTML = '3分钟搞定你的爱情';
	}
}

// 写信页面内容
function showComposeMail() {
	DOM.composeMail.innerHTML = writeMailTemplate;
	// 初始化写信页面中用到的DOM元素
	DOM.mail_operate_message = $('mail.operate.message');
	DOM.upload_iframe_content = $('upload_iframe_content');
	DOM.compose_subject = $('compose.subject');
	DOM.compose_wto = $('compose.wto');
	DOM.compose_wcc = $('compose.wcc');
	DOM.compose_wbcc = $('compose.wbcc');
	DOM.securityCode = $('securityCode');
	// DOM.checkSign = $('checkSign');
	DOM.uploadInfoDIV = $('uploadInfoDIV');
	DOM.editor_mess2 = $('editor.mess2');
	// DOM.compose_editer = $('compose.editer');
	DOM.compose_mess1 = $('compose.mess1');
	DOM.compose_mess2 = $('compose.mess2');
	// DOM.user_sign_area = $('user_sign_area');
	DOM.mail_cc = $('mail.cc');
	DOM.mail_bcc = $('mail.bcc');
	DOM.writemail_area = $('writemail_area');
	DOM.saveCheckbox1 = $('saveCheckbox1');
	DOM.saveCheckbox2 = $('saveCheckbox2');
}

// 欢迎页内容展现
function showMainMail() {
	var _mp = DOM.mainPage ? DOM.mainPage : $('mainPage');
	_mp.innerHTML = mailMainTemplate;
	var _am = DOM.ad_main = DOM.ad_main ? DOM.ad_main : $('ad_main');
	_am.innerHTML = mailMainAdTemplate;
	var _maa = DOM.main_ad_area = DOM.main_ad_area ? DOM.main_ad_area : $('main_ad_area');
	try {
		_maa.addClassName('cn1-adw');
		DOM.ad_main.show();
	} catch(e) {}
}

// 发信成功页面内容
function showSendSucc() {
	$('sendSuc').update(sendMailSuccTemplate);
}

// commend推荐内容
function __commendContent() {
	var _commend = $('commend');
	try {
		if (sohuMailAds && sohuMailAds.homecenter && sohuMailAds.homecenter.show) {
			var _data_left = sohuMailAds && sohuMailAds.homecenter.left, _data_right = sohuMailAds && sohuMailAds.homecenter.right, _c_left = $('commend_left'), _c_right = $('serviceContent2'), _html = [];
			if (_c_left) 
				_c_left.innerHTML = '<a hidefocus="true" href="' + _data_left.href + '" target="_blank">' + _data_left.text + '</a>';
			$A(_data_right).each(function(item){
				if (item.img) {
					_html.push('<dt><img src="' + item.img + '" style="margin-right:3px;border:0px;" /><a hidefocus="true" href="' + item.href + '" target="_blank">' + item.text + '</a></dt>');
					return;
				}
				_html.push('<dt><a hidefocus="true" href="' + item.href + '" target="_blank">' + item.text + '</a></dt>');
			});
			if (_c_right) 
				_c_right.innerHTML = _html.join('');
		}
	} catch(e) {}
	var uinfo = USERINFO.evalJSON();
	if(typeof uinfo == 'object') {
		_commend.hide();
		get_postcard({}, function(ret) {
			PCTMP = ret;
			reBuildPostcardData(ret);
			var _cardlist = CARDLIST.evalJSON()[0];
			var tmp = [];
			for(var i=0;i<5;i++) {
				tmp.push('<div class="letter-normal s_postcard" pindex="0,'+ i +'"><img src="'+ MailConst.ALL +'/../../postcard/'+ _cardlist[i].tmpthumb +'" class="letter-image" /></div>');
			}
			Element.insert($('info'), {after: new Template(mainPostcardTemplate).evaluate({
				postcard_image: tmp.join('')
			})});
		});
		return false;
	}
	try {
		var l = $A(_commend.getElementsByTagName('iframe'));
	} catch(e) {}
	if(!l || l == null) return false;
	var homeads = [];
	try {
		if(sohuMailAds && sohuMailAds.homepage && sohuMailAds.homepage.show) {
			sohuMailAds.homepage.ads.each(function(item){
				homeads.push('<div style="height:22px;line-height:22px;overflow:hidden;"> ・ <a hidefocus="true" href="' + item.href + '" target="_blank">' + item.text + '</a></div>');
			});
		}
	} catch(e) {}
	try {
		var c = '<table border=0 cellspacing=0 cellpadding=0 width="100%" height="100%"><tbody><tr><td width="50%" height="100%" style="padding:0px 2px 0px 4px;">' + homeads.join('') + '</td><td width="50%" height="100%" style="padding:0px 2px 0px 4px;">' + sogoucommend + '</td></tr></tbody></table>';
		if (l.length == 0) {
			$("commendcontent").innerHTML = c;
		}
	} catch(e) {}
}

function commendContent() {
	var _commend = $('commend');
	try {
		if (sohuMailAds && sohuMailAds.homecenter && sohuMailAds.homecenter.show) {
			var _data_right = sohuMailAds && sohuMailAds.homecenter.right, _c_right = $('service_tips'), _html = [];
			$A(_data_right).each(function(item){
				if (item.img) {
					_html.push('<div><img src="' + item.img + '" style="margin-right:3px;border:0px;" /><a hidefocus="true" href="' + item.href + '" target="_blank">' + item.text + '</a></div>');
					return;
				}
				_html.push('<div><a hidefocus="true" href="' + item.href + '" target="_blank">' + item.text + '</a></div>');
			});
			if (_c_right) 
				_c_right.innerHTML = _html.join('');
		}
	} catch(e) {}
	try {
		var homeads = [], homeads1 = [], homeads2 = [];
		if(sohuMailAds && sohuMailAds.homepage && sohuMailAds.homepage.show) {
			sohuMailAds.homepage.ads.each(function(item) {
				homeads.push('<div class="s-item"> ・ <a hidefocus="true" href="' + item.href + '" target="_blank">' + item.text + '</a></div>');
			});
		}
		homeads1 = homeads.slice(0, 4);
		homeads2 = homeads.slice(4);
		/*
		var _t = '<div class="s-area1">' + homeads.join('') + '</div>'
			+'<div class="s-area1">' + sogoucommend + '</div>';
			// +'<div class="s-area1" style="width:auto;">' + homeads.join('') + '</div>';
		*/
		var _t = '<table cellpadding="0" cellspacing="0" style="border:0;width:100%;"><col style="width:50%;"></col><col style="width:50%;"></col><tbody><tr>'
			+'<td><div class="s-area1">'+ homeads1.join('') +'</div></td>'
			+'<td><div class="s-area1">'+ homeads2.join('') +'</div></td>'
			+'</tr></tbody></table>';
		$('service_ads').innerHTML = _t;
	} catch(e) {}
	/*
	try {
		var l = $A(_commend.getElementsByTagName('iframe'));
	} catch(e) {}
	if(!l || l == null) return false;
	var homeads = [];
	try {
		if(sohuMailAds && sohuMailAds.homepage && sohuMailAds.homepage.show) {
			sohuMailAds.homepage.ads.each(function(item){
				homeads.push('<div style="height:22px;line-height:22px;overflow:hidden;"> ・ <a hidefocus="true" href="' + item.href + '" target="_blank">' + item.text + '</a></div>');
			});
		}
	} catch(e) {}
	try {
		var c = '<table border=0 cellspacing=0 cellpadding=0 width="100%" height="100%"><tbody><tr><td width="50%" height="100%" style="padding:0px 2px 0px 4px;">' + homeads.join('') + '</td><td width="50%" height="100%" style="padding:0px 2px 0px 4px;">' + sogoucommend + '</td></tr></tbody></table>';
		if (l.length == 0) {
			$("commendcontent").innerHTML = c;
		}
	} catch(e) {}
	*/
}

// 用户欢迎页面的图片广告
function imageAdsContent() {
	if(!sohuMailAds) return false;
	if(!sohuMailAds.homeimage) return false;
	var _had = USE_SYS.name == 'chinaren' ? sohuMailAds.homeimage_chinaren : sohuMailAds.homeimage;
	if(!_had.href && !_had.img) return false;
	if(!_had.show) return false;
	try {
		var _div = document.createElement('div');
		_div.className = 'clear';
		_div.style.marginBottom = '10px';
		_div.style.backgroundImage = 'url('+ _had.img +')';
		_div.style.width = '490px';
		_div.style.height = '100px';
		_div.style.fontSize = '0px';
		_div.innerHTML = '<a hidefocus="true" href="'+ _had.href +'" target="_blank" style="width:100%;height:100%;">&nbsp;</a>';
		Element.insert($('info'), {after: _div});
		MailEffect.SlideDown(_div);
	} catch(e) {}
}


// 头部区域的事件代理
function tpEventDelegation() {
	var _tmp_dl = [
		{name: 's_mainpage', event: function(event) {
			jsoplog.ucCapture( 'mailindex' );
			changePanel('mainPage');
		}},
		{name: 's_logout', event: function(event) {
			jsoplog.ucCapture( 'mailexit' );
			doLogout();
		}},
		{name: 's_config', event: function(event) {
			jsoplog.ucCapture( 'mailconfig' );
			changePanel('mailConfiguration', 'initMailCfg');
		}},
		{name: 's_change_skin', event: function(event, EL) {
			jsoplog.ucCapture( 'changeskin' );
			changePanel('mailConfiguration', 'initChangeSkin');
		}},
		{name: 's_lab', event: function(event, EL) {
			changePanel('mailConfiguration', 'initLab');
		}},
		{name: 's_overview_c', event: function(event, EL) {
			MLMD('conference');
			EL = $(EL);
			/*
			try {
				EL.removeClassName('s_overview_c');
				EL.innerHTML = '返回普通模式';
			} catch(e) {}
			*/
			try {
				var _tc = setTimeout(function() {
					clearTimeout(_tc);
					_tc = null;
					// EL.addClassName('s_con_c');
					EL.className = '';
					EL.innerHTML = '';
					_dialog.alert({title:'温馨提示：',info:'您的邮箱已成功切换到会话模式！<br />要返回普通模式，请进入“选项” --> “基本设置”中关闭会话模式。'});
				}, 500);
			} catch(e) {}
			try {
				jsoplog.ucCapture('useconference');
			} catch(e) {}
		}},
		{name: 's_con_c', event: function(event, EL) {
			MLMD('mail');
			EL = $(EL);
			try {
				EL.removeClassName('s_con_c');
				EL.innerHTML = '体验会话模式';
			} catch(e) {}
			try {
				var _tc = setTimeout(function() {
					clearTimeout(_tc);
					_tc = null;
					EL.addClassName('s_overview_c');
				}, 500);
			} catch(e) {}
			try {
				jsoplog.ucCapture('usecommon');
			} catch(e) {}
		}},
		{name: 's_search_web', event: function(event, EL) {
			searchSogou('search_web_content');
			jsoplog.ucCapture('searchweb');
			// searchMail();
		}},
		{name: 's_search_mail', event: function(event, EL) {
			searchMail();
			jsoplog.ucCapture('searchmail');
		}},
		{name: 's_reload', event: function(event, EL) {
			window.location.reload(true);
		}}
		/*,
		{name: 's_search_other', event: function(event, EL) {
			var e = EL.previousSibling;
			var mlist = [{
            	text: '搜索网页',
            	onclick: function(){
					searchSogou('search_mail_content');
					jsoplog.ucCapture('searchweb');
                	return false;
            	}
        	}];
			menu.showMenu(EL.parentNode, DOM.sohuMailMain, mlist, 'menu menu-search', true, null, event);
		}}
		*/
	];
	
	DOM.navbg.observe('click', function(event) {
		var el = event.target;
		_tmp_dl.each(function(item) {
			if($(el).hasClassName(item.name)) {
				eventStop(event);
				item.event(event, el);
				if(el.nodeName.toLowerCase() == 'a') {
					el.blur();
				}
				return false;
			}
		});
	});
	
	$('search_web_content').observe('keypress', function(event) {
		if(event.keyCode == 13) {
			searchSogou('search_web_content');
			jsoplog.ucCapture('searchweb');
		}
	});
	
	$('search_mail_content').observe('keydown', function(event) {
		if(event.keyCode == 13) {
			searchMail();
			jsoplog.ucCapture('searchmail');
		}
	}).observe('focus', function(event) {
		var _isa = this.getAttribute('isActive');
		if(_isa && _isa == 'true') return false;
		$(this).removeClassName('input-grey').value = '';
		this.setAttribute('isActive', 'true');
	});
}

// 左侧列表的事件代理
function lfEventDelegation() {
	var _tmp_dl = [
		{name: 's_checkmail', event: function(event) {
			checkNewMail(true);
			jsoplog.ucCapture('mailcheck');
            jsoplog.sendPV('checkmail');
		}},
		{name: 's_writemail', event: function(event) {
			changePanel('composeMail');
			// changeLeftButton('s_writemail');
			jsoplog.ucCapture('mailwrite');
            jsoplog.sendPV('composemail');
		}},
		{name: 's_address', event: function(event) {
			changePanel('contactList');
			jsoplog.ucCapture('mailaddress');
            jsoplog.sendPV('contact');
		}},
		{name: 's_unread', event: function(event) {
			changePanel('mailList', -2);
			jsoplog.ucCapture('mailunread');
            jsoplog.sendPV('unread');
		}},
		{name: 's_inbox', event: function(event) {
			changePanel('mailList', 1);
			jsoplog.ucCapture('mailinbox');
            jsoplog.sendPV('inbox');
		}},
		{name: 's_starmail', event: function(event) {
                        if(isConferenceMode){
                           mailConference.clearListCache(-5);
                        }
                        else{
                            mailList.clearListCache();
                        }
			changePanel('mailList', -5);
			jsoplog.ucCapture('mailstarbox');
                        jsoplog.sendPV('starbox');
		}},
		{name: 's_draft', event: function(event) {
			changePanel('mailList', 2);
			jsoplog.ucCapture('maildraft');
            jsoplog.sendPV('draft');
		}},
		{name: 's_send', event: function(event) {
			changePanel('mailList', 3);
			jsoplog.ucCapture('mailsent');
            jsoplog.sendPV('sent');
		}},
		{name: 's_delete', event: function(event) {
			changePanel('mailList', 4);
			jsoplog.ucCapture('maildelete');
            jsoplog.sendPV('trash');
		}},
		{name: 's_junk', event: function(event) {
			changePanel('mailList', 5);
			jsoplog.ucCapture('mailgabage');
            jsoplog.sendPV('junk');
		}},
		{name: 's_myfolder_', event: function(event) {
			if(arguments[1]) {
				var _el = arguments[1], _cn = 's_myfolder_', _fid,
				_id = _el.className.split(' ');
				_id.each(function(item) {
					if(item.include(_cn)) _fid = item;
				});
				_fid = _fid.split('_')[2];
				if (_fid && typeof (_fid*1) == 'number') {
                	changePanel('mailList', _fid);
                    jsoplog.ucCapture('mailfolder' + _fid);
                    jsoplog.sendPV('folder' + _fid);
				}
			}
		}},
		{name: 's_foldermanage', event: function(event) {
			changePanel('newFolderList');
			jsoplog.ucCapture('mailuserfolder');
		}},
		{name: 's_foldercreate', event: function(event) {
			changePanel('addFolderList');
			jsoplog.ucCapture('mailaddfolder');
		}},
		{name: 's_daishoumanage', event: function(event) {
			// mailPop.getPop3List();
			changePanel('popManage');
			jsoplog.ucCapture('daishoumanage');
		}},
		{name: 's_daishoucreate', event: function(event) {
			// mailPop.setPop3Account();
			changePanel('popCreate');
			$('ID_IPT_POPUID').focus();
			jsoplog.ucCapture('daishoucreate');
		}},
		{name: 's_score', event: function(event) {
			changePanel('score');
			jsoplog.ucCapture( 'mailscore' );
		}},
		{name: 's_greetcard', event: function(event) {
			changePanel('card');
			jsoplog.ucCapture( 'mailcard' );
		}},
		{name: 's_mainpage', event: function(event) {
			changePanel('mainPage');
			jsoplog.ucCapture( 'mailindex' );
		}},
		{name: 's_config', event: function(event) {
			changePanel('mailConfiguration', 'initMailCfg');
			jsoplog.ucCapture( 'mailconfig' );
		}}        
	];
	var _gpcn = Element.getParentNodeByClassName;
	DOM.left.observe('mousedown', function(event) {
		if(!Event.isLeftClick(event)) return false;
		var el = event.target;
		_tmp_dl.each(function(item) {
			if(item.name == 's_myfolder_') {
				var e = _gpcn(el, item.name, true);
			} else {
				var e = _gpcn(el, item.name);
			}
			if(e) {
				eventStop(event);
				item.event(event, e);
				return false;
			}
		});
	}).observe('click', function(event) {
		var el = event.target;
		if(el.nodeName.toLowerCase() == 'a' || el.getAttribute('role') == 'link') {
			el.blur();
			if(!el.getAttribute('target'))Event.stop(event);
			return false;
		}		
	});
	
    //
    var nodes = $$(".s_udisk_entrance");
    nodes.each(function(item){
        item.onclick = function(event){
            jsoplog.ucCapture('udisk_click_left');
            return showUdiskPanel.apply(this);
        }
    })
}

// 首页面的事件代理
function mainEventDelegation() {
	var _tmp_dl = [
		{name: 's_postcard', event: function(EL, event) {
			// var e = Element.hasClassName(EL, 's_postcard') ? EL : Element.hasClassName(EL.parentNode, 's_postcard') ? EL.parentNode : null;
			if (EL) {
				var pindex = EL.pindex ? EL.pindex : EL.getAttribute('pindex');
				pindex = pindex.split(',');
				writecardmail.init(null, pindex);
			}
		}}, {name: 's_task_contact', event: function(EL, event) {
			hiddenAllPanel();
			DOM.addressGroupList.show();
			mailAddressClass.createContact(null, 1);
		}}, {name: 's_gift_contact', event: function(EL, event) {
			get_newbee_type('get_prise', 'add_contact', 2, null, 'true');
		}}, {name: 's_task_letter', event: function(EL, event) {
			changePanel('composeMail', null, null, null, 1);
			var _html = '<div style="text-indent:2em;">您好！我新注册了一个邮箱，地址是：'+ UserSohuID +'，请添加到您的地址簿，以后跟我联系可以给这个邮箱发信！</div><br />祝一切顺利！<br />';
			var _t = setTimeout(function() {
				clearTimeout(_t);
				_t = null;
				var _c = _html + writemail.getContentInput();
				writemail.setContentInput(_c);
				writemail.content = writemail.getContentInput();
			}, 100);
		}}, {name: 's_wap_mail', event: function(EL, event) {
			changePanel('wapConfiguration');
			jsoplog.ucCapture('wap');
		}}, {name: 's_udisk', event: function(EL, event) {
			jsoplog.ucCapture('udisk_help');
		}}, {name: 's_gift_letter', event: function(EL, event) {
			get_newbee_type('get_prise', 'write_letter', 2, null, 'true');
		}}, {name: 's_task_friends', event: function(EL, event) {
			var _iv = is_invite_friends ? 0 : 1;
			writecardmail.init(null, null, _iv);
		}}, {name: 's_gift_friends', event: function(EL, event) {
			get_newbee_type('get_prise', 'invite_friends', 1, null, 'true');
		}}, {name: 's_all_gift', event: function(EL, event) {
			get_newbee_type('complete_mission', 'magic', 1, null, 'true');
		}}, {name: 's_read_mail', event: function(EL, event) {
			var mid = EL.getAttribute('mid');
			try {
				if (isConferenceMode) {
					mailConference.folder = 1;
					mailConference.getMailRead(mid);
				} else {
					try {
						mailList.currentFolder = 1;
						mailRead._prev_page = null, mailRead._next_page = 1;
						mailRead.folder = 1;
						mailRead.page = 0;
						mailRead.getMailRead(mid);
					} catch(e) {}
				}
			} catch(e) { }
		}}, {name: 's_reply_mail', event: function(EL, event) {
			var mid = EL.getAttribute('mid');
			try {
				if(isConferenceMode) {
					mailConference.folder = 1;
					mailConference.read_mail_callback_exec = function() {
						mailConference.replyMail(mailConference._last_id, 'replyall');
					};
					mailConference.getMailRead(mid);
				} else {
					mail_read({id: mid}, function(ret) {
						mailRead.currentMail = ret;
						mailRead.replyMail('reply');
					});
				}
			} catch(e) { }
		}}, {name: 's_compose_mail', event: function(EL, event) {
			changePanel('composeMail');
		}}, {name: 's_compose_card_mail', event: function(EL, event) {
			changePanel('composeCardMail');
		}},
		{name: 's_mobile_mail', event: function(EL, event) {
			changePanel('mobileConfiguration');
			jsoplog.ucCapture('mailmobile');
		}},
		{name: 's_skin_mail', event: function(EL, event) {
			changePanel('mailConfiguration', 'initChangeSkin');
			jsoplog.ucCapture( 'changeskin' );
		}},
		{name: 's_lab_mail', event: function(EL, event) {
			changePanel('mailConfiguration', 'initLab');
		}},
		{name: 's_custom_mail', event: function(EL, event) {
			changePanel('userMail');
		}},
		{name: 's_pop_mail', event: function(EL, event) {
			changePanel('popCreate');
		}}
	];
	DOM.mainPage.observe('click', function(event) {
		var EL = $(event.target);
		_tmp_dl.each(function(item) {
			var e = Element.getParentNodeByClassName(EL, item.name);
			if(e) {
				item.event(e, event);
				if(!e.getAttribute('target')) Event.stop(event);
			}
		});
		return false;
	}).observe('mouseover', function(event) {
		var EL = $(event.target);
		var e = Element.getParentNodeByClassName(EL, 's_postcard');
		if(e) {
			try {
				Element.addClassName(e, 'letter-over');
			} catch(e) {}
			Event.stop(event);
		}
		return false;
	}).observe('mouseout', function(event) {
		var EL = $(event.target);
		var e = Element.getParentNodeByClassName(EL, 's_postcard');
		if(e) {
			try {
				Element.removeClassName(e, 'letter-over');
			} catch(e) {}
			Event.stop(event);
		}
		return false;
	});
}


// 发信成功页面显示
function sendSuccess() {
	DOM.sendSuc.show();
	try {
		var _crad = $('chinaren_ad');
		if(!_crad.firstChild || !succbanner.include(_crad.firstChild.src)) {
			if(USE_SYS.name != 'sohu') return false;
			setTimeout(function() {
				_crad.innerHTML = succbanner;
			}, 50);
		}
	} catch(e) {}
}

// 邮件首页显示
function mailMainPage() {
	/*
	try {
		if (isDefaultListPage) {
			changePanel('mailList', 1);
			isDefaultListPage = false;
			return false;
		}
	} catch(e) {}
	*/
	hiddenAllPanel(true);
	try {
		DOM.main_ad_area.addClassName('cn1-adw');
		DOM.ad_main.show();
	} catch(e) {}
	changeToolbarStyle('');
	DOM.mainPage.show();
	try {
		setUserInfo();
	} catch(e) {}
	try {
		deleteLoadPage();
	} catch(e) {}
	try {
		mailScore(__SCORE);
	} catch(e) {}
	try {
		addAjaxHistory('mailMain', 'changePanel("mainPage", null, true)', '搜狐', arguments[0]);
	} catch(e) {}
}

// 载入广告
// 只在登录邮箱之后进行载入
function loadAds() {
	var _ad = $('ad');
	try {
		_ad.innerHTML = '<div id="ad_new" style="margin-bottom:10px;"></div>' + (USE_SYS.name == 'sohu' ? voteOnline : '');
	} catch(e) {}
	// 为新疆用户单独投放的广告
	var _ad_main = function(el) {
		try {
			if(_is_xj) {
				$(el).observe('click', function(event) {
					mailPop.setPop3Account();
				}).setStyle({cursor:'pointer'}).innerHTML = '<img src="'+ MailConst.ALL +'/xj.20100324.gif" />';
			} else {
				el.innerHTML = homebig;
			}
		} catch(e) {
			el.innerHTML = homebig;
		}
	};
    try {
        var uinfo = USERINFO.evalJSON();
		var _adn = $('ad_new');
		if(typeof uinfo == 'object') {
			init_tourial_list(uinfo);
		} else {
			// _adn.innerHTML = homebig;
			_ad_main(_adn);
		}
    } catch(e){
		// _adn.innerHTML = homebig;
		_ad_main(_adn);
	}
	try {
		if(USE_SYS.name == 'sohu') createVote();
	} catch(e) {}
}


// add by zhangyinghui
function createVote() {
	var voteAjax = new Ajax.Request('/activity/vote/vote.jsp', {
		method: 'get', 
		onComplete: function(req) {
			var _id_vote = $('ID_VOTEONLINE');
			_id_vote.innerHTML = ['<ul>', req.responseText, '</ul>'].join('');
			_id_vote = null;
		}
	});
	voteAjax = null;
}


//获取积分及可兑换奖品信息
function getScore() {
	params={needproductinfo:1};
	_defun('/score/getscore', 'post', params, mailScore);
}

//获取发信成功页显示积分信息
function getScoreInfo(){
	_defun('/score/getscoreinfo', 'get', {}, sendMailScoreInfo);
}

function sendMailScoreInfo(ret){
	$('promptGift').innerHTML="<br />"+ret;
}

function showRightAds(id, is_show) {
	if(is_show) {
		var iframes = $(id).getElementsByTagName("iframe");
		//显示cs的
		var _left = DOM.readMail.getWidth() + staticValue.leftWidth - staticValue.rightAdsWidth + staticValue.rightAdsRight + 'px';
		var _right_ads = $("ID_RIGHT_ADS");
		if(Element.visible(iframes[0])){
			Element.show(iframes[1]);
			Element.hide(iframes[0]);
			_right_ads.style.display = 'none';
			Element.setStyle($(id), {right:staticValue.rightAdsRight+'px', top:staticValue.rightAdsTop1+'px', left:''});
			_right_ads.parentNode.style.height = staticValue.rightAdsHeight1+'px';
		} else{//显示sogou的
			Element.show(iframes[0]);
			Element.hide(iframes[1]);
			_right_ads.style.display = 'block';
			Element.setStyle($(id), {right:staticValue.rightAdsRight+'px', top:staticValue.rightAdsTop2+'px', left:''});
			_right_ads.parentNode.style.height = staticValue.rightAdsHeight2+'px';
		}
		if(!Element.visible($(id))) {
			Element.show($(id));
		}
		if(mailConference._mail_content_is_max) {
			Element.setStyle($(id), {left:_left});
		}
	} else {
		if(Element.visible($(id))) {
			Element.hide($(id));
			Element.setStyle($(id), {left:'-5000px', top:'-5000px', right:''});
		}
	}
}


// 初始化页面panel的DOM节点
function initPanelDOM() {
	DOM.sohuMailMain = DOM.sohuMailMain ? DOM.sohuMailMain : $('sohuMailMain');
	DOM.mainPage = DOM.mainPage ? DOM.mainPage : $('mainPage');
	DOM.composeCardMail = DOM.composeCardMail ? DOM.composeCardMail : $('composeCardMail');
	DOM.composeMail = DOM.composeMail ? DOM.composeMail : $('composeMail');
	DOM.sendSuc = DOM.sendSuc ? DOM.sendSuc : $('sendSuc');
	DOM.mailList = DOM.mailList ? DOM.mailList : $('mailList');
	DOM.mailSearch = DOM.mailSearch ? DOM.mailSearch : $('mailSearch');
	DOM.newFolderList = DOM.newFolderList ? DOM.newFolderList : $('newFolderList');
	DOM.readMail = DOM.readMail ? DOM.readMail : $('readMail');
	DOM.addressGroupList = DOM.addressGroupList ? DOM.addressGroupList : $('addressGroupList');
	DOM.mailConfiguration = DOM.mailConfiguration ? DOM.mailConfiguration : $('mailConfiguration');
	DOM.mobileConfiguration = DOM.mobileConfiguration ? DOM.mobileConfiguration : $('mobileConfiguration');
	// DOM.customMail = DOM.customMail ? DOM.customMail : $('customMail');
	DOM.left = DOM.left ? DOM.left : $('left');
	DOM.navbg = DOM.navbg ? DOM.navbg : $('navbg');
	// 用户自建文件夹区域
	DOM.newfolderArea = DOM.newfolderArea ? DOM.newfolderArea : $('newfolderArea');
	DOM.right = DOM.right ? DOM.right : $('right');
	DOM.right_content = DOM.right_content ? DOM.right_content : $('right_content');
}

// 读信页面右侧的广告
function rightAdsPoll(el1, el2) {
	if(_is_xj) return false;
	try {
		var _rd1 = $(el1), _rd2 = $(el2);
		if (!this._flag_rd) 
			this._flag_rd = 0;
		if (this._flag_rd % 2 == 0) {
			_rd1.show();
			_rd2.hide();
		} else {
			_rd1.hide();
			_rd2.show();
		}
		this._flag_rd++;
	} catch (e) { }
}


// 加载PV js
function loadPVjs() {
	//加载PV
	function m_s(){
		var c = escape((new Date().getTime()) * 1000 + Math.round(Math.random() * 1000));
		r = (typeof(encodeURI) == 'function') ? encodeURI(document.referrer) : document.referrer;
		if (document.cookie.indexOf("SUV=") < 0 || document.cookie.indexOf("IPLOC=") < 0) {
			var pv_script = document.createElement('script');
			pv_script.setAttribute('src', 'http://suvset.sohu.com/suv/" + c + "');
			document.body.appendChild(pv_script);
		}
		var _script = document.createElement('script');
		// img.setAttribute('id', 'pv_img_id');
        //pv加入宽高要求
        //alva - 2009/06/16
        var screen_w = window.screen.width;
        var screen_h = window.screen.height;
		_script.setAttribute('src', 'http://pv.sohu.com/pv.gif?t?='+c+ "_"+screen_w+"_"+screen_h+'?r?='+r);
		document.body.appendChild(_script);
	}
	var spv;if(!spv)m_s();spv=1;
}


/*------ start 新手上路 -------*/
// add by alva
// 初始化新手任务的框框  init_tourial_list
function init_tourial_list(uinfo){
    var _adn = $('ad_new');
    var NEWBEE_GETSCORE = 2
    var NEWBEE_COMPLETE = 1
    var NEWBEE_UNDO = 0
    var t = new Template(TOURIAL_TEMPLATE);
    var data = {};
    var HTMLS = {
		add_contact: ['<input type="button" class="am task s_task_contact" value="" />', '<input type="button" class="am gift s_gift_contact" value="" />', '<span class="score-end">已领取</span>'],
        write_letter: ['<input type="button" class="am task s_task_letter" value="" />', '<input type="button" class="am gift s_gift_letter" value="" />', '<span class="score-end">已领取</span>'],
		invite_friends: ['<input type="button" class="am task s_task_friends" value="" />', '<input type="button" class="am gift s_gift_friends" value="" />', '<span class="score-end">已领取</span>'],
		magic: ['已经完成所有任务,请领取<input type="button" class="am button-gift s_all_gift" value="神秘礼包" />', '已经领取<b class="orange">神秘礼包</b>！', '30天内完成全部任务，领取<b class="orange">神秘礼包</b>！']
    };
    
    data["ADD_CONTACT"] = HTMLS['add_contact'][uinfo["add_contact"]];
    data["WRITE_LETTER"] = HTMLS['write_letter'][uinfo["write_letter"]];
    data["INVITE_FRIEND"] = HTMLS['invite_friends'][uinfo["invite_friends"]];
    // data["ADD_POP"] = HTMLS['add_pop'][uinfo["add_pop"]];
    var is_magic = true;
    // var key_var = ['add_contact', 'write_letter', 'invite_friends', 'add_pop'];
	var key_var = ['add_contact', 'write_letter', 'invite_friends'];
    for (var i = 0; i < key_var.length; i++) {
        if (uinfo[key_var[i]] == 0) {
            is_magic = false;
            break;
        }
    }
    data['MAGIC'] = HTMLS['magic'][uinfo['magic']];
    if (uinfo["magic"] == 1) {
        data["MAGIC"] = HTMLS['magic'][1];
    }
    else {
        if (is_magic) {
            data['MAGIC'] = HTMLS['magic'][0];
        }
        else {
            data['MAGIC'] = HTMLS['magic'][2];
        }
    }
    _adn.innerHTML = t.evaluate(data);
}

var is_invite_friends = false;
// 发送事件, 以及callback, 这个写的还可以,嘎嘎
function get_newbee_type(func, type, type_status, last_type, is_callback){
    if (!type_status) {
        type_status = 1;
    }
    if (!last_type) {
        last_type = 'list';
    }
	if(type == 'invite_friends') is_invite_friends = true;
    var uid = UserSohuID;
    var SECRET = {
        list: 'fjdFE.ze4#BDa',
        add_contact: 'f1d2sa$#&*(',
        write_letter: 'fdsa$#@!qsad',
        invite_friends: 'f3ewqr$#',
        add_pop: 'ip,/.dcsas#',
        magic: 'fdasfd,m#WEI'
    };
    var token = hex_md5([uid, type, type_status, SECRET[type]].join(''));
    var paras = {
        'token': token,
        'type': type,
        'type_status': type_status,
        'last_type': last_type,
		'is_callback' : is_callback
    };
	TAjax[func](paras, tourial_complete_success.bind(tourial_complete_success, paras));
}

// success tourial_complete_success
function tourial_complete_success(paras, ret) {
    if (paras['type'] == 'list') {
		if (paras['is_callback']) {
			var _t_w = document.viewport.getWidth();
			var _t_h = document.viewport.getHeight();
			var ele = new Element("div", {
				id: "tourial_hidden"
			});
			ele.setStyle({
				background:"black",
				position: "absolute",
				width: _t_w + "px",
				height: _t_h + "px",
				left: document.viewport.getScrollOffsets().left + "px",
				top: document.viewport.getScrollOffsets().top + "px",
				zIndex: 999999,
				opacity: 0.6
			});
			// ele.setOpacity(0.3);
			var pri = new Element("div", {
				id: 'tourial_prize'
			});
			var desc = {
				'add_contact': {
					index: 3,
					score: 40
				},
				'write_letter': {
					index: 1,
					score: 20
				},
				'invite_friends': {
					index: 2,
					score: 30
				},
				'add_pop': {
					index: 4,
					score: 50
				}
			}
			var _png_css = "background:url('"+ MailConst.ALL +"/closebox.png') no-repeat !important;background:none;filter:none !important; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+ MailConst.ALL +"/closebox.png');width:30px;height:30px;margin-top:-36px;cursor:pointer;";
			try {
				var s = '';
				if (paras['last_type'] == 'magic') {
					pri.setStyle({
						width: "382px",
						height: "215px",
						left: ((_t_w / 2 - 300)) + "px",
						top: (_t_h / 2 - 150) + "px",
						position: "absolute",
						zIndex: 9999999
					});
					s = '<div class="info" style="width:340px;border:1px solid #f1c14e;background:#fefceb;padding:30px;"><h3 class="orange" style="margin:5px 0px;width:150px;">神秘礼包</h3><div class="s_close_float" style="float:right;'+ _png_css +'"></div><li>恭喜你完成全部新手任务。我们送给您送来一个神秘礼包，看看里面是什么吧！</li><li> 恭喜你获得：</li><li style="margin-top:8px;"><img src="' + MailConst.ACTI + '/image/letao.gif" class="oline" /><img src="' + MailConst.ACTI + '/image/xiangce.jpg" class="oline" /><img src="' + MailConst.ALL + '/image/d1.jpg" class="oline" /></li><li style="margin-top:8px;">快去您的邮箱里查收吧！  </li></div>';
				}
				else {
					pri.setStyle({
						width: "340px",
						height: "170px",
						left: ((_t_w / 2 - 300)) + "px",
						top: (_t_h / 2 - 150) + "px",
						position: "absolute",
						zIndex: 9999999
					});
					s = '<div class="info" style="width:300px;border:1px solid #f1c14e;background:#fefceb;padding:30px;"><h3 class="orange" style="margin:5px 0px;width:150px;">做任务，领积分</h3><div class="s_close_float" style="float:right;'+ _png_css +'"></div><li>恭喜你完成第' + desc[paras['last_type']]['index'] + '项任务。我们赠送您 <b class="orange">' + desc[paras['last_type']]['score'] + '</b>个积分。</li><li> 现在您有更多的积分了，可以兑换：</li><li style="margin-top:8px;"><img src="' + MailConst.ALL + '/score1.jpg" class="oline"/><img src="' + MailConst.ALL + '/score2.jpg" class="oline"/><img src="' + MailConst.ALL + '/score3.jpg" class="oline"/><a hidefocus="true" href="http://score.mail.sohu.com/product.action" target="_blank">>>更多奖品</a></li><li style="margin-top:8px;">快去看看还有什么奖品吧！   <a hidefocus="true" href="http://score.mail.sohu.com/product.action" target="_blank" >Go >></a></li></div>';
				}
			} catch (e) {
				var s = 'Oooops,系统出现了一些小意外,它可能太累了.让它稍后休息下!';
			}
			pri.innerHTML = s;
			$(document.body).insert(ele);
			$(document.body).insert(pri);
			try {
				Event.observe(pri, 'click', function(event) {
					var EL = event.target;
					if(Element.hasClassName(EL, 's_close_float')) {
						ele.parentNode.removeChild(ele);
						pri.parentNode.removeChild(pri);
						Event.stop(event);
						return false;
					}
				});
			} catch(e) {}
		}
        if (ret.status == true) {
            init_tourial_list(ret.msg);
        } else { }
        return;
    }
    try {
        get_newbee_type('get_mission', 'list', 1, paras['type'], paras['is_callback']);
    } catch (e) { }
}

function tourial_complete_failed(ret){
}
/*------ end 新手上路 --------*/

//收件人数量限制的过滤器
function receiverFilterBeforeSendMail(p){
	var num = 0;
	for (var key in p){
		if (p[key] instanceof Array)
			num += p[key].length;
	}
	if(num > G.maxReceiverNum){

		_dialog.alert({info: '最多只能有20个收件人地址'});
		return false;		 
	 }// end if
	 return true;
}
//发件前的过滤器 需要添加 直接加入即可
function filterBeforeSendMail(p){
	var ret = receiverFilterBeforeSendMail(p);
	return ret;
}
